<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE book PUBLIC "-//OASIS//DTD DocBook XML V4.2//EN"
"file:/d:/docbook/dtd/docbookx.dtd">

<book>
<bookinfo>
    <title>Box2D v2.0.1 User Manual</title>
    <author><firstname>Erin</firstname><surname>Catto</surname></author>
    <copyright><year>2007-2008</year><holder>Erin Catto</holder></copyright>
</bookinfo>

<chapter>
    <title>Introduction</title>
    <sect1>
    <title>About</title>
    <para>Box2D is a 2D rigid body simulation library for games. Programmer&apos;s can use it in their games to make objects move in believable ways and make the world seem more interactive. From the game&apos;s point of view a physics engine is just a system for procedural animation. Rather than paying (or begging) an animator to move your actors around, you can let Sir Isaac Newton do the directing.</para>
    <para>Box2D is written in portable C++. Most of the types defined in the engine begin with the <emphasis>b2</emphasis> prefix. Hopefully this is sufficient to avoid name clashing with your game engine.</para>
</sect1>

  <sect1>
    <title>Prerequisites</title>
    <para>In this manual I&apos;ll assume you are familiar with basic physics concepts, such as mass, force, torque, and impulses. If not, please first consult the many tutorials provided by Chris Hecker and David Baraff (google these names). You do not need to understand their tutorials in great detail, but they do a good job of laying out the basic concepts that will help you use Box2D.</para>
    <para><ulink url="http://wikipedia.org">Wikipedia</ulink> is also an excellent source of physics and mathematics knowledge. In some ways it is more useful than Google, because it has carefully crafted content.</para>
    <para>This is not a prerequisite, but if you are curious about the about the inner workings of Box2D, you can look at these <ulink url="http://www.gphysics.com/downloads">articles</ulink>.</para>
    <para>Since Box2D is written in C++, you are expected to be experienced in C++ programming. Box2D should not be your first C++ programming project. You should be comfortable with compiling, linking, and debugging.</para>
  </sect1>
  
  <sect1>
    <title>Core Concepts</title>
    <para>Box2D works with several fundamental objects. We briefly define these objects here and more details are given later in this document.</para>
    <glosslist>
      <glossentry>
        <glossterm>rigid body</glossterm>
        <glossdef>
          <para>A chunk of matter that is so strong that the distance between any two bits of matter on the chunk is completely constant. They are hard like a diamond. In the following discussion we use <emphasis>body</emphasis> interchangably with rigid body.</para>
        </glossdef>
      </glossentry>
      <glossentry>
        <glossterm>shape</glossterm>
        <glossdef>
          <para>A 2D piece of collision geometry that is rigidly attached to a body. Shapes have
          material properties of friction and restitution.</para>
        </glossdef>
      </glossentry>
      <glossentry>
        <glossterm>constraint</glossterm>
        <glossdef>
          <para>A constraint is a physical connection that removes degrees of freedom from bodies. In 2D a body has 3 degrees of freedom. If we take a body and pin it to the wall (like a pendulum) we have <emphasis>constrained</emphasis> the body to the wall. At this point the body can only rotate about the pin, so the constraint has removed 2 degrees of freedom.</para>
        </glossdef>
      </glossentry>
      <glossentry>
        <glossterm>contact constraint</glossterm>
        <glossdef>
          <para>A special constraint designed to prevent penetration of rigid bodies and to simulate friction and restitution. You will never create a contact constraint, they are created automatically by Box2D.</para>
        </glossdef>
      </glossentry>
      <glossentry>
        <glossterm>joint</glossterm>
        <glossdef>
          <para>This is a contraint used to hold two or more bodies together. Box2D supports these joint types: revolute, prismatic, distance, and more. Joints may support <emphasis>limits</emphasis> and <emphasis>motors</emphasis>.</para>
        </glossdef>
      </glossentry>
      <glossentry>
        <glossterm>joint limit</glossterm>
        <glossdef>
          <para>A joint limit restricts the range of motion of a joint. For example, the human elbow only allows a certain range of angles.</para>
        </glossdef>
      </glossentry>
      <glossentry>
        <glossterm>joint motor</glossterm>
        <glossdef>
          <para>A joint motor drives the motion of the connected bodies according to the joint&apos;s degrees of freedom. For example, you can use a motor to drive the rotation of an elbow.</para>
        </glossdef>
      </glossentry>
      <glossentry>
        <glossterm>world</glossterm>
        <glossdef>
          <para>A physics world is a collection of bodies, shapes, and constraints that interact together. Box2D supports the creation of multiple worlds, but this is usually not necessary or desirable.</para>
        </glossdef>
      </glossentry>
    </glosslist>
    </sect1>
</chapter>
  
<chapter>
    <title>Hello Box2D</title>
    <para>In the distribution of Box2D is a <emphasis>Hello World</emphasis> project. The program creates a large ground box and a small dynamic box. This code does not contain any graphics, so prepare to be underwelmed. :)</para>

    <sect1>
      <title>Creating a World</title>
      <para>Every Box2D program begins with the creation of a world object. This is the physics hub that manages memory, objects, and simulation.</para>
      <para>To create a world object, first we need to define a bounding box for the world. Box2D uses the bounding box to accelerate collision detection. The size isn&apos;t critical, but a better fit will improve performance. It is better to make the box too big than to make it too small.</para>
      <programlisting>
b2AABB worldAABB;
worldAABB.lowerBound.Set(-100.0f, -100.0f);
worldAABB.upperBound.Set(100.0f, 100.0f);
</programlisting>
      <caution>
        <para>The <emphasis>world AABB</emphasis> should always be bigger then the region where your bodies are located. It is better to make the world AABB too big than too small. If a body reaches the boundary of the world AABB it will be frozen and will stop simulating.</para>
      </caution>
      <para>Next we define the gravity vector. Yes, you can make gravity go sideways (or you could just rotate your monitor). Also we tell the world to allow bodies to sleep when they come to rest. A sleeping body doesn&apos;t require any simulation.</para>
      <programlisting>
b2Vec2 gravity(0.0f, -10.0f);
bool doSleep = true;
</programlisting>
      <para>Now we create the world object. Normally you would create the world on the heap and store the pointer in one of your game structures. However, creating the world on the stack works fine in this example.</para>
      <programlisting>
b2World world(worldAABB, gravity, doSleep);
</programlisting>
      <para>So now we have our physics world, let&apos;s start adding some stuff to it.</para>
    </sect1>
    
    <sect1>
      <title>Creating a Ground Box</title>
      <para>Bodies are built using the following steps:</para>
      <orderedlist>
        <listitem>
          <para> Define a body with a position, damping, etc.</para>
        </listitem>
        <listitem>
          <para> Use the world object to create the body.</para>
        </listitem>
        <listitem>
          <para> Define shapes with geometry, friction, density, etc.</para>
        </listitem>
        <listitem>
          <para> Create shapes on the body.</para>
        </listitem>
        <listitem>
          <para> Optionally adjust the body&apos;s mass to match the attached shapes.</para>
        </listitem>
      </orderedlist>
      <para>For step 1 we create the ground body. For this we need a <emphasis>body definition</emphasis>. With the body definition we specify the initial position of the ground body.</para>
      <programlisting>
b2BodyDef groundBodyDef;
groundBodyDef.position.Set(0.0f, -10.0f);
</programlisting>
      <para>For step 2 the body definition is passed to the world object to create the ground body. The world object does not keep a reference to the body definition. The ground body is created as a static body. Static bodies don&apos;t collide with other static bodies and are immovable. Box2D determines that a body is static when it has zero mass. Bodies have zero mass by default, therefore they are static by default.</para>
      <programlisting>
b2Body* ground = world.CreateBody(&amp;groundBodyDef);
</programlisting>
      <para>For step 3 we create a ground polygon definition. We use the <literal>SetAsBox</literal> shortcut to form the ground polygon into a box shape, with the box centered on the origin of the parent body.</para>
      <programlisting>
b2PolygonDef groundShapeDef;
groundShapeDef.SetAsBox(50.0f, 10.0f);
</programlisting>
      <para>The <function>SetAsBox</function> function takes the half-width and half-height. So in this case the ground box is 100 units wide (x-axis) and 20 units tall (y-axis). Box2D is tuned for meters, kilograms, and seconds. So you can consider the extents to be in meters. However, it is possible to change unit systems, as discussed later in this document</para>
      <para>We finish the ground body in step 4 by creating the ground polygon shape on the ground body.</para>
      <programlisting>
groundBody-&gt;CreateShape(&amp;groundShapeDef);
</programlisting>
      <para>Again, Box2D does not keep a reference to the shape or body definitions. It copies the data into the <classname>b2Body</classname> structure.</para>
      <para>Note that every shape must have a parent body, even shapes that are static. However, you can attach all static shapes to a single static body. This need for static bodies is done to make the Box2D code more uniform internally, reducing the number of potential bugs.</para>
      <para>You might notice a pattern here. Most Box2D types are prefixed with <literal>b2</literal>. This is done to reduce the chance for naming conflicts with your code.</para>
    </sect1>
    <sect1>
      <title>Creating a Dynamic Body</title>
      <para>So now we have a ground body. We can use the same technique to create a dynamic body. The main difference, besides dimensions, is that we must establish the dynamic body&apos;s mass properties.</para>
      <para>First we create the body using <function>CreateBody</function>.</para>
      <programlisting>
b2BodyDef bodyDef;
bodyDef.position.Set(0.0f, 4.0f);
b2Body* body = world.CreateBody(&amp;bodyDef);
</programlisting>
      <para>Next we create and attach a polygon shape. Notice that we set density to 1. The default density is zero. Also, the friction on the shape is set to 0.3. Once the shape is attached, we instruct the body to compute it&apos;s mass properties from the attached shapes using the method <function>SetMassFromShapes</function>. This gives you a hint that you can attach more than one shape per body. If the computed mass is zero, then the body becomes truly static. Bodies have a mass of zero by default, that&apos;s why we didn&apos;t need to call <function>SetMassFromShapes</function> for the ground body.</para>
      <programlisting>
b2PolygonDef shapeDef;
shapeDef.SetAsBox(1.0f, 1.0f);
shapeDef.density = 1.0f;
shapeDef.friction = 0.3f;
body-&gt;CreateShape(&amp;shapeDef);
body-&gt;SetMassFromShapes();
</programlisting>
      <para>That&apos;s it for initialization. We are now ready to begin simulating.</para>
    </sect1>
    
    <sect1>
      <title>Simulating the World (of Box2D)</title>
      <para>So we have initialized the ground box and a dynamic box. Now we are ready to set Newton loose to do his thing. We just have a couple more issues to consider.</para>
      <para>Box2D uses a bit of numerical code called an <emphasis>integrator</emphasis>. Integrators simulate the physics equations at discrete points of time. This goes along with the traditional game loop where we essentially have a flip book of movement on the screen. So we need to pick a time step for Box2D. Generally physics engines for games like a time step at least as fast as 60Hz or 1/60 seconds. You can get away with larger time steps, but you will have to be more careful about setting up the definitions for your world. We also don&apos;t like the time step to change much. So don&apos;t tie the time step to your frame rate (unless you really, really have to). Without further ado, here is the time step.</para>
      <programlisting>
float32 timeStep = 1.0f / 60.0f;
</programlisting>
      <para>In addition to the integrator, Box2D also uses a larger bit of code called a <emphasis>constraint solver</emphasis>. The constraint solver solves all the constraints in the simulation, one at a time. A single constraint can be solved perfectly. However, when we solve one constraint, we slightly disrupt other constraints. To get a good solution, we need to iterate over all constraints a number of times. The suggested iteration count for Box2D is 10. You can tune this number to your liking, just keep in mind that this has a trade-off between speed and accuracy. Using fewer iterations increases performance but accuracy suffers. Likewise, using more iterations decreases performance but improves the quality of your simulation. Here is our chosen iteration count.</para>
      <programlisting>
int32 iterations = 10;
</programlisting>
        <para>Note that the time step and the iteration count are completely unrelated. An iteration is not a sub-step. One iteration is a single pass over all the constraints withing a time step. You can have multiple passes over the constraints within a single time step.</para>
      <para>We are now ready to begin the simulation loop. In your game the simulation loop can be merged with your game loop. In each pass through your game loop you call <literal>b2World::Step</literal>. Just one call is usually enough, depending on your frame rate and your physics time step.</para>
      <para>The Hello World program was designed to be dead simple, so it has no graphical output. Rather that being utterly boring by producing no output, the code prints out the position and rotation of the dynamic body. Yay! Here is the simulation loop that simulates 60 time steps for a total of 1 second of simulated time.</para>
      <programlisting>
for (int32 i = 0; i &lt; 60; ++i)
{
    world.Step(timeStep, iterations);
    b2Vec2 position = body-&gt;GetPosition();
    float32 angle = body-&gt;GetAngle();
    printf(&quot;%4.2f %4.2f %4.2f\n&quot;, position.x, position.y, angle);
}
</programlisting>
    </sect1>
    
    <sect1>
      <title>Cleanup</title>
      <para>When a world leaves scope or is deleted by calling <literal>delete</literal> on a pointer, all the memory reserved for bodies and joints is freed. This is done to make your life easier. However, you will need to nullify any body, shape, or joint pointers you have because they will become invalid.</para>
    </sect1>

    <sect1>
    <title>The Testbed</title>
    <para>Once you have conquered the HelloWorld example, you should start looking at Box2D&apos;s testbed. The testbed is a unit-testing framework and demo environment. Here are some of the features:</para>
    <itemizedlist>
      <listitem>
        <para> Camera with pan and zoom.</para>
      </listitem>
      <listitem>
        <para> Mouse picking of shapes attached to dynamic bodies.</para>
      </listitem>
      <listitem>
        <para> Extensible set of tests.</para>
      </listitem>
      <listitem>
        <para> GUI for selecting tests, parameter tuning, and debug drawing options.</para>
      </listitem>
      <listitem>
        <para> Pause and single step simulation.</para>
      </listitem>
      <listitem>
        <para> Text rendering.</para>
      </listitem>
    </itemizedlist>
    <screenshot>
      <mediaobject>
        <imageobject>
          <imagedata fileref="images/testbed.gif" format="GIF"/>
        </imageobject>
      </mediaobject>
    </screenshot>
     <para>The testbed has many examples of Box2D usage in the test cases and the framework itself. I encourage you to explore and tinker with the testbed as you learn Box2D.</para>
    <para><emphasis>Note:</emphasis> the testbed is written using <ulink url="http://freeglut.sourceforge.net/">freeglut</ulink> and <ulink url="http://www.cs.unc.edu/~rademach/glui/">GLUI</ulink>. The testbed is not part of the Box2D library. Box2D is agnostic about rendering. As shown by the HelloWorld example, you don&apos;t need a renderer to use Box2D.</para>
    </sect1>
</chapter>
  
  
<chapter>
    <title>API Design</title>
    <sect1>
      <title>Memory Management</title>
      <para>A large number of the decisions about the design of Box2D were based on the need for quick and efficient use of memory. In this section I will discuss how and why Box2D allocates memory.</para>
      <para>Box2D tends to allocate a large number of small objects (around 50-300 bytes). Using the system heap through <literal>malloc</literal> or <literal>new</literal> for small objects is inefficient and can cause fragmentation. Many of these small objects may have a short life span, such as contacts, but can persist for several time steps. So we need an allocator that can efficiently provide heap memory for these objects.</para>
      <para>Box2D&apos;s solution is to use a <emphasis>small object</emphasis> allocator (SOA). The SOA keeps a number of growable pools of varying sizes. When a request is made for memory, the SOA returns a block of memory that best fits the requested size. When a block is freed, it is returned to the pool. Both of these operations are fast and cause little heap traffic.</para>
      <para>Since Box2D uses a SOA, you should never <emphasis>new</emphasis> or <emphasis>malloc</emphasis> a body, shape, or joint. You do have to allocate a <classname>b2World</classname>. The <classname>b2World</classname> class provides factories for you to create bodies, shapes, and joints. This allows Box2D to use the SOA and hide the gory details from you. Never, ever, call <literal>delete</literal> or <literal>free</literal> on a body, shape, or joint.</para>
      <para>While executing a time step, Box2D needs some temporary workspace memory. For this, it uses a stack allocator to avoid per-step heap allocations. You don&apos;t need to interact with the stack allocator, but it&apos;s good to know it&apos;s there.</para>
    </sect1>
    
    <sect1>
      <title>Factories and Definitions</title>
      <para>As mentioned above, memory management plays a central role in the design of the Box2D API. So when you create a <classname>b2Body</classname> or a <classname>b2Joint</classname>, you need to call the factory functions on <classname>b2World</classname>.</para>
      <para>There are creation functions:</para>
      <programlisting>
b2Body* b2World::CreateBody(const b2BodyDef* def)
b2Joint* b2World::CreateJoint(const b2JointDef* def)
</programlisting>
      <para>And there are corresponding destruction functions:</para>
      <programlisting>
void b2World::DestroyBody(b2Body* body)
void b2World::DestroyJoint(b2Joint* joint)
</programlisting>
      <para>When you create a body or joint, you need to provide a <emphasis>definition</emphasis> or <emphasis>def</emphasis> for short. These definitions contain all the information needed to build the body or joint. By using this approach we can prevent construction errors, keep the number of function parameters small, provide sensible defaults, and reduce the number of accessors.</para>
      <para>Since shapes musted be parented to a body, they are created and destroyed using a factory method on <classname>b2Body</classname>:</para>
      <programlisting>
b2Shape* b2Body::CreateShape(const b2ShapeDef* def)
void b2Body::DestroyShape(b2Shape* shape)
</programlisting>
      <para>Factories do not retain references to the definitions. So you can create definitions on the stack and keep them in temporary resources.</para>
    </sect1>
    
    <sect1 id="units">
        <title>Units</title>
        <para>Box2D works with floating point numbers, so some tolerances have to be used to make Box2D perform well. These tolerance have been tuned to work well with meters-kilogram-second (MKS) units. In particular, Box2D has been tuned to work well with moving objects between 0.1 and 10 meters. So this means objects between soup cans and buses in size should work well.</para>
        <para>Being a 2D physics engine it is tempting to use pixels as your units. Unfortunately this will lead to a poor simulation and possibly weird behavior. An object of length 200 pixels would be seen by Box2D as the size of a 45 story building. Imagine trying to simulate the movement of a high-rise building with an engine that is tuned to simulate ragdolls and barrels. It isn't pretty.</para>
        <caution>
            <para>Box2D is tuned for MKS units. Keep the size of moving objects roughly between 0.1 and 10 meters. You'll need to use some scaling system when you render your environment and actors. The Box2D examples do this by using an OpenGL viewport transform.</para>
        </caution>
</sect1>
    
    <sect1>
      <title>User Data</title>
      <para>The <classname>b2Shape</classname>, <classname>b2Body</classname>, and <classname>b2Joint</classname> classes allow you to attach user data as a <literal>void</literal> pointer. This is handy when you are examining Box2D data structures and you want to determine how they relate to the data structures in your game engine.</para>
      <para>For example, it is typical to attach an <emphasis>actor</emphasis> pointer to the rigid body on that actor. This sets up a circular reference. If you have the actor, you can get the body. If you have the body, you can get the actor.</para>
      <programlisting>
GameActor* actor = GameCreateActor();
b2BodyDef bodyDef;
bodyDef.userData = actor;
actor-&gt;body = box2Dworld-&gt;CreateBody(&amp;bodyDef);
</programlisting>
      <para>Here are some examples of cases where you would need the user data:</para>
      <itemizedlist>
        <listitem>
          <para> Applying damage to an actor using a collision result.</para>
        </listitem>
        <listitem>
          <para> Playing a scripted event if the player is inside an axis-aligned box.</para>
        </listitem>
        <listitem>
          <para> Accessing a game structure when Box2D notifies you that a joint is going to be destroyed.</para>
        </listitem>
      </itemizedlist>
      <para>Keep in mind that user data is optional and you can put anything in it. However, you should be consistent. For example, if you want to store an actor pointer on one body, you should keep an actor pointer on all bodies. Don&apos;t store an actor pointer on one body, and a foo pointer on another body. This will likely lead to a crash if you try to cast an actor pointer into a foo pointer.</para>
    </sect1>
    
    <sect1>
      <title>Dealing with C++</title>
      <para>C++ is great for encapsulation and polymorphism, but it&apos;s not so great for API design. There are always significant trade-offs when creating a C++ library.</para>
      <para>Should we use abstract factories or the <emphasis>pimpl</emphasis> idiom? These make the API look cleaner, but they ultimately get in the way of debugging and efficient development.</para>
      <para>Should we use private data and friends as necessary? Perhaps, but eventually the number of friends can become ridiculous.</para>
      <para>Should we just wrap the C++ code with a C-API? Perhaps, but this is extra work and may lead to internal choices that are non-optimal. Also, C-APIs are harder to debug and maintain. A C-API also breaks encapsulation.</para>
      <para>For Box2D I have chosen the path of least resistance. For some cases a class is well contained in its design and function, so I use public functions and private data. For everything else I use classes or structs with all public members. These choices let me develop the code rapidly, it is easy to debug, and it creates minimal internal clutter while maintaining tight encapsulation. The downside is that you don&apos;t see a clean, simple API. Of course, you have this nice manual to help you out. :)</para>
    </sect1>
    <sect1>
      <title>Strawman</title>
      <para>If you don&apos;t like this API design, that&apos;s ok! You have the source code! Seriously, if you have feedback about anything related to Box2D, please leave a comment in the <ulink url="http://www.box2d.org/forum">forum</ulink>.</para>
    </sect1>
  </chapter>
  
  
<chapter>
    <title>The World</title>
    <sect1>
        <title>About</title>
        <para>The <classname>b2World</classname> class contains the bodies and joints. It manages all aspects of the simulation and allows for asynchronous queries (like AABB queries). Much of your interactions with Box2D will be with a <classname>b2World</classname> object.</para>
    </sect1>
    <sect1>
      <title>Creating and Destroying a World</title>
      <para>Creating a world is fairly simple. You need to provide a bounding box and a gravity vector.</para>
      <para>The axis-aligned bounding box should encapsulate the world. You can improve performance by making the bounding box a bit bigger than your world, say 2x just to be safe. If you have lots of bodies that fall into the abyss, your should detect this and remove the bodies. This will improve performance and prevent floating point overflow.</para>
      <para>To create and destory a world you need to use <literal>new</literal> and <literal>delete</literal>.</para>
      <programlisting>
b2World* myWorld = new b2World(aabb, gravity, doSleep);
... do stuff ...
delete myWorld;
</programlisting>
      <caution>
        <para>Recall that the <emphasis>world AABB</emphasis> should always be bigger then the region where your bodies are located. If bodies leave the world AABB, then they will be frozen. This is not a bug.</para>
      </caution>
    </sect1>
    <sect1>
      <title>Using a World</title>
      <para>The world class contains factories for creating and destroying bodies and joints. These factories are discussed later in the sections on bodies and joints. There are some other interactions with <classname>b2World</classname> that I will cover now.</para>
      <sect2>
        <title>Simulation</title>
        <para>The world class is used to drive the simulation. You specify a time step and an iteration count. For example:</para>
        <programlisting>
float32 timeStep = 1.0f / 60.f;
int32 iterationCount = 10;
myWorld-&gt;Step(timeStep, iterationCount);
</programlisting>
        <para>After the time step you can examine your bodies and joints for information. Most likely you will grab the position off the bodies so that you can update your actors and render them. You can perform the time step anywhere in your game loop, but you should be aware of the order of things. For example, you must create bodies before the time step if you want to get collision results for the new bodies in that frame.</para>
        <para>As I discussed above in the HelloWorld tutorial, you should use a fixed time step. By using a larger time step you can improve performance in low frame rate scenarios. But generally you should use a time step no larger than 1/30 seconds. A time step of 1/60 seconds will usually deliver a high quality simulation.</para>
        <para>The iteration count controls how many times the constraint solver sweeps over all the contacts and joints in the world. More iterations always yields a better simulation. But don&apos;t trade a small time step for a large iteration count. 60Hz and 10 iterations is far better than 30Hz and 20 iterations.</para>
      </sect2>
      <sect2>
        <title>Exploring the World</title>
        <para>As mentioned before, the world is a container for bodies and joints. You can grab the body and joint lists off the world and iterate over them. For example, this code wakes up all the bodies in the world:</para>
        <programlisting>
for (b2Body* b = myWorld-&gt;GetBodyList(); b; b = b-&gt;GetNext())
{
    b-&gt;WakeUp();
}
</programlisting>
        <para>Unfortunately life can be more complicated. For example, the following code is broken:</para>
        <programlisting>
for (b2Body* b = myWorld-&gt;GetBodyList(); b; b = b-&gt;GetNext())
{
    GameActor* myActor = (GameActor*)b-&gt;GetUserData();
    if (myActor->IsDead())
    {
        myWorld-&gt;DestroyBody(b); // ERROR: now GetNext returns garbage.
    }
}
</programlisting>
        <para>Everything goes ok until a body is destroyed. Once a body is destroyed, its next pointer becomes invalid. So the call to <methodname>b2Body::GetNext()</methodname> will return garbage. The solution to this is to copy the next pointer before destroying the body.</para>
        <programlisting>
b2Body* node = myWorld-&gt;GetBodyList();
while (node)
{
    b2Body* b = node;
    node = node->GetNext();
    
    GameActor* myActor = (GameActor*)b-&gt;GetUserData();
    if (myActor->IsDead())
    {
        myWorld-&gt;DestroyBody(b);
    }
}
</programlisting>
        <para>This safely destroys the current body. However, you may want to call a game function that may destroy multiple bodies. In this case you need to be very careful. The solution is application specific, but for convenience I'll show one method of solving the problem.</para>
        <programlisting>
b2Body* node = myWorld-&gt;GetBodyList();
while (node)
{
    b2Body* b = node;
    node = node->GetNext();
    
    GameActor* myActor = (GameActor*)b-&gt;GetUserData();
    if (myActor->IsDead())
    {
        bool otherBodiesDestroyed = GameCrazyBodyDestroyer(b);
        if (otherBodiesDestroyed)
        {
            node = myWorld-&gt;GetBodyList();
        }
    }
}
</programlisting>
        <para>Obviously to make this work, <function>GameCrazyBodyDestroyer</function> must be honest about what it has destroyed.</para>
      </sect2>
      <sect2>
        <title>AABB Queries</title>
        <para>Sometimes you want to determine all the shapes in a region. The <classname>b2World</classname> class has a fast log(N) method for this using the <emphasis>broad-phase</emphasis> data structure. You provide an AABB in world coordinates and <classname>b2World</classname> returns an array of all the shapes that potentially intersect the AABB. This is not exact because what the function actually does is return all the shapes whose AABBs intersect the specified AABB. For example, the following code finds all the shapes that potentially intersect a specified AABB and wakes up all of the associated bodies.</para>
        <programlisting>
b2AABB aabb;
aabb.minVertex.Set(-1.0f, -1.0f);
aabb.maxVertex.Set(1.0f, 1.0f);
const int32 k_bufferSize = 10;
b2Shape *buffer[k_bufferSize];
int32 count = myWorld-&gt;Query(aabb, buffer, k_bufferSize);
for (int32 i = 0; i &lt; count; ++i)
{
    buffer[i]-&gt;GetBody()-&gt;WakeUp();
}
</programlisting>
      </sect2>
    </sect1>
</chapter>
  
  
  
<chapter>
    <title>Bodies</title>
    <sect1>
        <title>About</title>
        <para>Bodies have position and velocity. You can apply forces, torques, and impulses to bodies. Bodies can be static or dynamic. Static bodies never move and don&apos;t collide with other static bodies.</para>
        <para>Bodies are the backbone for shapes. Bodies carry shapes and move them around in the world. Bodies are always <emphasis>rigid bodies</emphasis> in Box2D. That means that two shapes attached to the same rigid body never move relative to each other.</para>
        <para>You usually keep pointers to all the bodies you create. This way you can query the body positions to update the positions of your graphical entities. You should also keep body pointers so you can destroy them when you are done with them.</para>
    </sect1>
    <sect1>
      <title>Body Definition</title>
      <para>Before a body is created you must create a body definition (<classname>b2BodyDef</classname>). You can create a body definition on the stack or build it into your game&apos;s data structures. The choice is up to you.</para>
      <para>Box2D copies the data out of the body definition, it does not keep a pointer to the body definition. This means you can recycle a body definition to create multiple bodies.</para>
      <para>Lets go over some of the key members of the body definition.</para>
      <sect2>
        <title>Mass Properties</title>
        <para>There are a few ways to establish the mass properties for a body.</para>
        <orderedlist>
          <listitem>
            <para> Set the mass properties explicitly in the body definition.</para>
          </listitem>
          <listitem>
            <para> Set the mass properties explicitly on the body (after it has been created).</para>
          </listitem>
          <listitem>
            <para> Set the mass properties based on the density of the attaced shapes.</para>
          </listitem>
        </orderedlist>
        <para>In many game scenarios it makes sense to compute mass based on shape densities. This helps to ensure that bodies have reasonable and consistent mass values.</para>
        <para>However, other game scenarios may require specific mass values. For example, you may have a mechanism, like a scale that needs precises mass values.</para>
        <para>You can explicitly set the mass properties in the body definition as follows:</para>
        <programlisting>
bodyDef.massData.mass = 2.0f;   // the body&apos;s mass in kg
bodyDef.center.SetZero();       // the center of mass in local coordinates
bodyDef.I = 3.0f;               // the rotational inertia in kg*m^2.
    </programlisting>
        <para>The other methods of setting the mass properties are covered elsewhere in this document.</para>
      </sect2>
      <sect2>
        <title>Position and Angle</title>
        <para>The body definition gives you the chance to initialize the position of the body on creation. This has better performance than creating the body at the world origin and then moving the body.</para>
        <para>A body has two main points of interest. The first point is the body&apos;s <emphasis>origin</emphasis>. Shapes and joints are attached relative to the body&apos;s origin. The second point of interest is the <emphasis>center of mass</emphasis>. The center of mass is determined from mass distribution of the attached shapes or is explicitly set with <classname>b2MassData</classname>. Much of Box2D&apos;s internal computations use the center of mass position. For example <classname>b2Body</classname> stores the linear velocity for the center of mass.</para>
        <para>When you are building the body definition, you may not know where the center of mass is located. Therefore you specify the position of the body&apos;s origin. You may also specify the body&apos;s angle in radians, which is not affected by the position of the center of mass. If you later change the mass properties of the body, then the center of mass may move on the body, but the origin position does not change and the attached shapes and joints do not move.</para>
        <programlisting>
bodyDef.position.Set(0.0f, 2.0f);   // the body&apos;s origin position.
bodyDef.angle = 0.25f * b2_pi;      // the body&apos;s angle in radians.
</programlisting>
      </sect2>
      <sect2>
        <title>Damping</title>
        <para>Damping is used to reduce the world velocity of bodies. Damping is different than friction because friction only occurs with contact and damping is much cheaper to simulate than friction. However, damping is not a replacement for friction and the two effects should be used together.</para>
        <para>Damping parameters should be between 0 and infinity, with 0 meaning no damping, and infinity meaning full damping. Normally you will use a damping value between 0 and 0.1. I generally do not use linear damping because it makes bodies look <emphasis>floaty</emphasis>.</para>
        <programlisting>
bodyDef.linearDamping = 0.0f;
bodyDef.angularDamping = 0.01f;
</programlisting>
        <para>Damping is approximated for stability and performance. At small damping values the damping effect is mostly independent of the time step. At larger damping values, the damping effect will vary with the time step. This is not an issue if you use a fixed time step (recommended).</para>
      </sect2>
      <sect2>
        <title>Sleep Parameters</title>
        <para>What does sleep mean? Well it is expensive to simulate bodies, so the less we have to simulate the better. When a body comes to rest we would like to stop simulating it.</para>
        <para>When Box2D determines that a body (or group of bodies) has come to rest, the body enters a sleep state which has very little CPU overhead. If an awake body collides with a sleeping body, then the sleeping body wakes up. Bodies will also wake up if a joint or contact attached to them is destroyed. You can also wake a body manually.</para>
        <para>The body definition lets you specify whether a body can <emphasis>sleep</emphasis> and whether a body is created sleeping.</para>
        <programlisting>
bodyDef.allowSleep = true;
bodyDef.isSleeping = false;
</programlisting>
      </sect2>
      <sect2 id="bullets">
        <title>Bullets</title>
        <para>Game simulation usually generates a sequence of images that are played at some frame rate. In this setting rigid bodies can move by a large amount in one time step. If a physics engine doesn&apos;t account for the large motion, you may see some objects incorrectly pass through each other. This effect is called <emphasis>tunneling</emphasis>.</para>
        <para>By default, Box2D uses continuous collision detection (CCD) to prevent dynamic bodies from tunneling through static bodies. This is done by sweeping shapes from their old position to their new positions. The engine looks for new collisions during the sweep and computes the time of impact (TOI) for these collisions. Bodies are moved to their first TOI and then simulated to the end of the original time step. This process is repeated as necessary.</para>
        <para>Normally CCD is not used between dynamic bodies. This is done to keep performance reasonable. In some game scenarios you need dynamic bodies to use CCD. For example, you may want to shoot a high speed bullet at a thin wall. Without CCD, the bullet my tunnel through the wall.</para>
        <para>Fast moving objects in Box2D are called bullets. You should decide what bodies should be bullets based on your game design. If you decide a body should be treated as a bullet, use the following setting.</para>
        <programlisting>
bodyDef.isBullet = true;
</programlisting>
        <para>The bullet flag only affects dynamic bodies.</para>
        <para>CCD is expensive so you probably don&apos;t want all moving bodies to be bullets. So by default Box2D only uses CCD between moving bodies and static bodies. This is an effective approach to prevent bodies from escaping your game world. However, you may have some fast moving bodies that that require CCD all the time.</para>
      </sect2>
    </sect1>
    <sect1>
      <title>Body Factory</title>
      <para>Bodies are created and destroyed using a body factory provided by the world class. This lets the world create the body with an efficient allocator and add the body to the world data structure.</para>
      <para>Bodies can be dynamic or static depending on the mass properties. Both body types use the same creation and destruction methods.</para>
      <programlisting>
b2Body* dynamicBody = myWorld-&gt;CreateBody(&amp;bodyDef);
... do stuff ...
myWorld-&gt;DestroyBody(dynamicBody);
dynamicBody = NULL;
</programlisting>
      <caution>
        <para><emphasis>Never</emphasis> use <literal>new</literal> or <literal>malloc</literal> to create a body. The world won&apos;t know about the body and the body won&apos;t be properly initialized.</para>
      </caution>
      <para>Static bodies do not move under the influence of other bodies. You may manually move static bodies, but you should be careful so that you don&apos;t squash dynamic bodies between two or more static bodies. Friction will not work correctly if you move a static body. Static bodies never simulate on their own and they never collide with other static bodies. It is faster to attach several shapes to a static body than to create several static bodies with a single shape on each one. Interally, Box2D sets the mass and inverse mass of static bodies to zero. This makes the math work out so that most algorithms don&apos;t need to treat static bodies as a special case.</para>
      <para>Box2D does not keep a reference to the body definition or any of the data it holds (except user data pointers). So you can create temporary body definitions and reuse the same body definitions.</para>
      <para>Box2D allows you to avoid destroying bodies by deleting your <classname>b2World</classname> object, which does all the cleanup work for you. However, you should be mindful to nullify any body pointers that you keep in your game engine.</para>
      <para>When you destroy a body, the attached shapes and joints are automatically destroyed. This has important implications for how you manage shape and joint pointers. See <xref linkend="implicit_destruction"/> for details.</para>
      <para>Suppose you want to connect a dynamic body to ground with a joint. You&apos;ll need to connect the joint to a static body. If you don&apos;t have a static body, you can get a shared ground body from your world object. You can also attach static shapes to the ground body.</para>
      <programlisting>
b2Body* ground = myWorld-&gt;GetGroundBody();
... build a joint using the ground body ...
</programlisting>
    </sect1>
    <sect1>
      <title>Using a Body</title>
      <para>After creating a body, there are many operations you can perform on the body. These include setting mass properties, accessing position and velocity, applying forces, and transforming points and vectors.</para>
      <sect2>
        <title>Mass Data</title>
        <para>You can adjust the mass of a body at run-time. This is usually done when you create or destroy shapes on a body. You may want to adjust the mass of the body based on the current shapes.</para>
        <programlisting>
void SetMassFromShapes();
</programlisting>
        <para>You may also want to set the mass properties directly. For example, you may change the shapes, but want to use your own mass formulas.</para>
        <programlisting>
void SetMass(const b2MassData* massData);
</programlisting>
        <para>The body&apos;s mass data is available through the following functions:</para>
        <programlisting>
float32 GetMass() const;
float32 GetInertia() const;
const b2Vec2&amp; GetLocalCenter() const;
</programlisting>
      </sect2>
      <sect2>
        <title>State Information</title>
        <para>There are many aspects to the body&apos;s state. You can access this state data efficient through the following functions:</para>
        <programlisting>
bool IsBullet() const;
void SetBullet(bool flag);

bool IsStatic() const;
bool IsDynamic() const;

bool IsFrozen() const;

bool IsSleeping() const;
void AllowSleeping(bool flag);
void WakeUp();
</programlisting>
        <para>The bullet state is described in <xref linkend="bullets"/>. The frozen state is described in <xref linkend="world_boundary"/>.</para>
      </sect2>
      <sect2>
        <title>Position and Velocity</title>
        <para>You access the position and rotation of a body. This is common when rendering your associated game actor. You can also set the position, although this is less common since you will normally use Box2D to simulate movement.</para>
        <programlisting>
bool SetXForm(const b2Vec2&amp; position, float32 angle);
const b2XForm&amp; GetXForm() const;
const b2Vec2&amp; GetPosition() const;
float32 GetAngle() const;
</programlisting>
        <para>You can access the center of mass position in world coordinates. Much of the internal simulation in Box2D uses the center of mass. However, you should normally not need to access it. Instead you will usually work with the body transform.</para>
        <programlisting>
const b2Vec2&amp; GetWorldCenter() const;
</programlisting>
        <para>You can access the linear and angular velocity. The linear velocity is for the center of mass.</para>
        <programlisting>
void SetLinearVelocity(const b2Vec2&amp; v);
b2Vec2 GetLinearVelocity() const;
void SetAngularVelocity(float32 omega);
float32 GetAngularVelocity() const;
</programlisting>
      </sect2>
      <sect2>
        <title>Forces and Impulses</title>
        <para>You can apply forces, torques, and impulses to a body. When you apply a force or an impulse, you provide a world point where the load is applied. This often results in a torque about the center of mass.</para>
        <programlisting>
void ApplyForce(const b2Vec2&amp; force, const b2Vec2&amp; point);
void ApplyTorque(float32 torque);
void ApplyImpulse(const b2Vec2&amp; impulse, const b2Vec2&amp; point);
</programlisting>
        <para>Applying a force, torque, or impulse wakes the body. Sometimes this is undesirable. For example, you may be applying a steady force and want to allow the body to sleep to improve performance. In this case you can use the following code.</para>
        <programlisting>
if (myBody-&gt;IsSleeping() == false)
{
    myBody-&gt;ApplyForce(myForce, myPoint);
}
</programlisting>
      </sect2>
      <sect2>
        <title>Coordinate Transformations</title>
        <para>The body class has some utility functions to help you transform points and vectors between local and world space. If you don&apos;t understand these concepts, please read &quot;Essential Mathematics for Games and Interactive Applications&quot; by Jim Van Verth and Lars Bishop. These functions are efficient, so use them with impunity.</para>
        <programlisting>
b2Vec2 GetWorldPoint(const b2Vec2&amp; localPoint);
b2Vec2 GetWorldVector(const b2Vec2&amp; localVector);
b2Vec2 GetLocalPoint(const b2Vec2&amp; worldPoint);
b2Vec2 GetLocalVector(const b2Vec2&amp; worldVector);
</programlisting>
      </sect2>
      <sect2>
        <title>Lists</title>
        <para>You can iterate over a body&apos;s shapes. This is mainly useful if you need to access the shape&apos;s user data.</para>
        <programlisting>
for (b2Shape* s = body-&gt;GetShapeList(); s; s = s-&gt;GetNext())
{
    MyShapeData* data = (MyShapeData*)s-&gt;GetUserData();
    ... do something with data ...
}
</programlisting>
        <para>You can similarly iterate over the body&apos;s joint list.</para>
      </sect2>
    </sect1>
  </chapter>
  
<chapter id="shapes">
    <title>Shapes</title>
    <sect1>
        <title>About</title>
        <para>Shapes are the collision geometry attached to bodies. Shapes are also used to define the mass of a body. This lets you specify the density and let Box2D do the work of computing the mass properties.</para>
        <para>Shapes have properties of friction and restitution. Shapes carry collision filtering information to let you prevent collisions between certain game objects.</para>
        <para>Shapes are always owned by a body. You can attach multiple shapes to a single body. Shapes are abstract classes so that many types of shapes can be implemented in Box2D. If you are brave, you can implement your own shape type (and collision algorithms).</para>
    </sect1>
    <sect1>
      <title>The Shape Definition</title>
      <para>Shape definitions are used to create shapes. There is common shape data held by <classname>b2ShapeDef</classname> and specific shape data held by derived classes.</para>
      <sect2>
        <title>Friction and Restitution</title>
        <para>Friction is used to make objects slide along each other realistically. Box2D supports static and dynamic friction, but uses the same parameter for both. Friction is simulated accurately in Box2D and the friction strength is proportional to the normal force (this is called <emphasis>Coulomb friction</emphasis>). The friction parameter is usually set between 0 and 1. A value of zero turns off friction and a value of one makes the friction strong. When the friction is computed between two shapes, Box2D must combine the friction parameters of the two shapes. This is done with the following formula:</para>
        <programlisting>
float32 friction;
friction = sqrtf(shape1-&gt;friction * shape2-&gt;friction);
</programlisting>
        <para>Restitution is used to make objects bounce. The restitution value is usually set to be between 0 and 1. Consider dropping a ball on a table. A value of zero means the ball won&apos;t bounce. This is called an <emphasis>inelastic</emphasis> collision. A value of one means the ball&apos;s velocity will be exactly reflected. This is called a <emphasis>perfectly elastic</emphasis> collision. Restitution is combined using the following formula.</para>
        <programlisting>
float32 restitution;
restitution = b2Max(shape1-&gt;restitution, shape2-&gt;restitution);
</programlisting>
        <para>When a shape develops multiple contacts, restitution is simulated approximately. This is because Box2D uses an iterative solver. Box2D also uses inelastic collisions when the collision velocity is small. This is done to prevent jitter.</para>
      </sect2>
      <sect2>
        <title>Density</title>
        <para>Box2D optionally computes the mass and rotational inertia of bodies using the mass distribution implied by the attached shapes. Specifying mass directly can often lead to poorly tuned simulations. Therefore, the recommended way of specifying body mass is by setting the shape densities and calling <literal>b2Body::SetMassFromShape</literal> once all the shapes are attached to the body.</para>
      </sect2>
      <sect2>
        <title>Filtering</title>
        <para>Collision filtering is a system for preventing collision between shapes. For example, say you make a character that rides a bicycle. You want the bicycle to collide with the terrain and the character to collide with the terrain, but you don&apos;t want the character to collide with the bicycle (because they must overlap). Box2D supports such collision filtering using categories and groups.</para>
        <para>Box2D supports 16 collision categories. For each shape you can specify which category it belongs to. You also specify what other categories this shape can collide with. For example, you could specify in a multiplayer game that all players don&apos;t collide with each other and monsters don&apos;t collide with each other, but players and monsters should collide. This is done with <emphasis>masking bits</emphasis>. For example:</para>
        <programlisting>
playerShapeDef.filter.categoryBits = 0x0002;
monsterShapeDef.filter.categoryBits = 0x0004;
playerShape.filter.maskBits = 0x0004;
monsterShapeDef.filter.maskBits = 0x0002;
</programlisting>
        <para>Collision groups let you specify an integral group index. You can have all shapes with the same group index always collide (positive index) or never collide (negative index). Group indices are usually used for things that are somehow related, like the parts of a bicycle. In the following example, shape1 and shape2 always collide, but shape3 and shape4 never collide.</para>
        <programlisting>
shape1Def.filter.groupIndex = 2;
shape2Def.filter.groupIndex = 2;
shape3Def.filter.groupIndex = -8;
shape4Def.filter.groupIndex = -8;
</programlisting>
        <para>Collisions between shapes of different group indices are filtered according the category and mask bits. In other words, group filtering has higher precendence than category filtering.</para>
        <para>Note that additional collision filtering occurs in Box2D. Here is a list:</para>
        <itemizedlist>
          <listitem>
            <para> A shape on a static body never collides with a shape on another static body.</para>
          </listitem>
          <listitem>
            <para> Shapes on the same body never collide with each other.</para>
          </listitem>
          <listitem>
            <para> You can optionally enable/disable collision between shapes on bodies connected by a joint.</para>
          </listitem>
        </itemizedlist>
        <para>Sometimes you might need to change collision filtering after a shape has already been created. You can get and set the <structname>b2FilterData</structname> structure on an existing shape using <function>b2Shape::GetFilterData</function> and <function>b2Shape::SetFilterData</function>. Box2D caches filtering results, so you must manually re-filter a shape using <function>b2World::Refilter</function>.</para>
      </sect2>
      <sect2>
        <title>Sensors</title>
        <para>Some times game logic needs to know when two shapes overlap yet there should be no collision response. This is done by using sensors. A sensor is a shape that detects collision but does not produce a response.</para>
        <para>You can flag any shape as being a sensor. Sensors may be static or dynamic. Remember that you may have multiple shapes per body and you can have any mix of sensors and solid shapes.</para>
        <programlisting>
myShapeDef.isSensor = true;
</programlisting>
      </sect2>
      <sect2>
        <title>Circle Definitions</title>
        <para><classname>b2CircleDef</classname> extends <classname>b2ShapeDef</classname> and adds a radius and a local position.</para>
        <programlisting>
b2CircleDef def;
def.radius = 1.5f;
def.localPosition.Set(1.0f, 0.0f);
</programlisting>
      </sect2>
      <sect2>
        <title>Polygon Definitions</title>
        <para><classname>b2PolyDef</classname> is used to implement convex polygons. They are a bit tricky to use correctly, so please read closely. The maximum vertex count is defined by <literal>b2_maxPolyVertices</literal> which is currently 8. If you need to use more vertices, you must modify <literal>b2_maxPolyVertices</literal> in <literal>b2Settings.h</literal>.</para>
        <para>When you build a polygon definition you must specify the number of vertices you will use. The vertices must be specified in <emphasis>counter-clockwise</emphasis> (CCW) order about the z-axis of a right-handed coordinate system. This might turn out to be clockwise on your screen, depending on your coordinate system conventions.</para>
        <para>Polygons must be <emphasis>convex</emphasis>. In other words, each vertex must point outwards to some degree. Finally, you must not overlap any vertices. Box2D will automatically close the loop.</para>
        <informalfigure>
          <mediaobject>
            <imageobject>
              <imagedata fileref="images/convex_concave.gif" format="GIF"/>
            </imageobject>
          </mediaobject>
        </informalfigure>
         <para>Here is an example of a polygon definition of a triangle:</para>
        <programlisting>
b2PolygonDef triangleDef;
triangleDef.vertexCount = 3;
triangleDef.vertices[0].Set(-1.0f, 0.0f);
triangleDef.vertices[1].Set(1.0f, 0.0f);
triangleDef.vertices[2].Set(0.0f, 2.0f);
</programlisting>
        <para>The vertices are defined in the coordinate system of the parent body. If you need to offset a polygon within the parent body, then just offset all the vertices.</para>
        <para>For convenience, there are functions to initialize polygons as boxes. You can have either an axis-aligned box centered at the body origin or an oriented box offset from the body origin.</para>
        <programlisting>
b2PolygonDef alignedBoxDef;
float32 hx = 1.0f; // half-width
float32 hy = 2.0f; // half-height
alignedBodyDef.SetAsBox(hx, hy);

b2PolygonDef orientedBoxDef;
b2Vec2 center(-1.5f, 0.0f);
float32 angle = 0.5f * b2_pi;
orientedBoxDef.SetAsBox(hx, hy, center, angle);
</programlisting>
      </sect2>
    </sect1>
    <sect1>
      <title>Shape Factory</title>
      <para>Shapes are created by initializing a shape definition and then passing the definition to the parent body.</para>
      <programlisting>
b2CircleDef circleDef;
circleDef.radius = 3.0f;
circleDef.density = 2.5f;
b2Shape* myShape = myBody-&gt;CreateShape(&amp;circleDef);
[optionally store shape pointer somewhere]
</programlisting>
      <para>This creates the shape and attaches it to the body. You do not need to store the shape pointer since the shape will automatically be destroyed when the parent body is destroyed (see <xref linkend="implicit_destruction"/>).</para>
      <para>After you finish adding shapes to a body, you may want to recompute the mass properties of the body based on the child shapes.</para>
      <programlisting>
myBody-&gt;SetMassFromShapes();
</programlisting>
      <para>This function is expensive, so you should only call it when necessary.</para>
      <para>You can destroy a shape on the parent body easily. You may do this to model a breakable object. Otherwise you can just leave the shape alone and let the body destruction take care of destroying the attached shapes.</para>
      <programlisting>
myBody-&gt;DestroyShape(myShape);
</programlisting>
      <para>After removing shapes from a body, you may want to call <literal>SetMassFromShapes</literal> again.</para>
    </sect1>
    <sect1>
      <title>Using a Shape</title>
      <para>There&apos;s not much to say here. You can get a shape&apos;s type and its parent body. You can also test a point to see if it is contained within the shape. Look at <literal>b2Shape.h</literal> for details.</para>
    </sect1>
</chapter>


<chapter>
    <title>Joints</title>
    <sect1>
        <title>About</title>
        <para>Joints are used to constrain bodies to the world or to each other. Typical examples in games include ragdolls, teeters, and pulleys. Joints can be combined in many different ways to create interesting motions.</para>
        <para>Some joints provide limits so you can control the range of motion. Some joint provide motors which can be used to drive the joint at a prescribed speed until a prescribed force/torque is exceeded.</para>
        <para>Joint motors can be used in many ways. You can use motors to control position by specifying a joint velocity that is proportional to the difference between the actual and desired position. You can also use motors to simulate joint friction: set the joint velocity to zero and provide a small, but significant maximum motor force/torque. Then the motor will attempt to keep the joint from moving until the load becomes too strong.</para>
    </sect1>
    <sect1>
      <title>The Joint Definition</title>
      <para>Each joint type has a definition that derives from <classname>b2JointDef</classname>. All joints are connected between two different bodies. One body may static. If you want to waste memory, then create a joint between two static bodies. :)</para>
      <para>You can specify user data for any joint type and you can provide a flag to prevent the attached bodies from colliding with each other. This is actually the default behavior and you must set the <literal>collideConnected</literal> Boolean to allow collision between to connected bodies.</para>
      <para>Many joint definitions require that you provide some geometric data. Often a joint will be defined by <emphasis>anchor points</emphasis>. These are points fixed in the attached bodies. Box2D requires these points to be specified in local coordinates. This way the joint can be specified even when the current body transforms violate the joint constraint --- a common ocurrence when a game is saved and reloaded. Additionally, some joint definitions need to know the default relative angle between the bodies. This is necessary to constraint rotation correctly via joint limits or a fixed relative angle.</para>
      <para>Initializing the geometric data can be tedious, so many joints have initialization functions that use the current body transforms to remove much of the work. However, these initialization functions should usually only be used for prototyping. Production code should define the geometry directly. This will make joint behavior more robust.</para>
      <para>The rest of the joint definition data depends on the joint type. We cover these now.</para>
      <sect2>
        <title>Distance Joint</title>
        <para>One of the simplest joint is a distance joint which says that the distance between two points on two bodies must be constant. When you specify a distance joint the two bodies should already be in place. Then you specify the two <emphasis>anchor</emphasis> points in world coordinates. The first anchor point is connected to body 1, and the second anchor point is connected to body 2. These points imply the length of the distance constraint.</para>
        <informalfigure>
          <mediaobject>
            <imageobject>
              <imagedata fileref="images/distanceJoint.gif" format="GIF"/>
            </imageobject>
          </mediaobject>
        </informalfigure>
         <para>Here is an example of a distance joint definition. In this case we decide to allow the bodies to collide.</para>
        <programlisting>
b2DistanceJointDef jointDef;
jointDef.Initialize(myBody1, myBody2, worldAnchorOnBody1, worldAnchorOnBody2);
jointDef.collideConnected = true;
</programlisting>
      </sect2>
      <sect2>
        <title>Revolute Joint</title>
        <para>A revolute joint forces two bodies to share a common anchor point, often called a <emphasis>hinge point</emphasis>. The revolute joint has a single degree of freedom: the relative rotation of the two bodies. This is called the <emphasis>joint angle</emphasis>.</para>
        <informalfigure>
          <mediaobject>
            <imageobject>
              <imagedata fileref="images/revoluteJoint.gif" format="GIF"/>
            </imageobject>
          </mediaobject>
        </informalfigure>
         <para>To specify a revolute you need to provide two bodies and a single anchor point in world space. The initialization function assumes that the bodies are already in the correct position.</para>
        <para>In this example, two bodies are connected by a revolute joint at the first body&apos;s center of mass.</para>
        <programlisting>
b2RevoluteJointDef jointDef;
jointDef.Initialize(myBody1, myBody2, myBody1-&gt;GetWorldCenter());
</programlisting>
        <para>The revolute joint angle is positive when body2 rotates CCW about the angle point. Like all angles in Box2D, the revolute angle is measured in radians. By convention the revolute joint angle is zero when the joint is created using <literal>Initialize()</literal>, regardless of the current rotation of the two bodies.</para>
        <para>In some cases you might wish to control the joint angle. For this, the revolute joint can optionally simulate a joint limit and/or a motor.</para>
        <para>A joint limit forces the joint angle to remain between an lower and upper bound. The limit will apply as much torque as needed to make this happen. The limit range should include zero, otherwise the joint will lurch when the simulation begins.</para>
        <para>A joint motor allows you to specify the joint speed (the time derivative of the angle). The speed can be negative or positive. A motor can have infinite force, but this is usually not desirable. Have you ever heard the expression:</para>
        <caution>
          <para>&quot;What happens when an irresistible force meets an immovable object?&quot;</para>
        </caution>
        <para>I can tell you it&apos;s not pretty. So you can provide a maximum torque for the joint motor. The joint motor will maintain the specified speed unless the required torque exceeds the specified maximum. When the maximum torque is exceeded, the joint will slow down and can even reverse.</para>
        <para>You can use a joint motor to simulate joint friction. Just set the joint speed to zero, and set the maximum torque to some small, but significant value. The motor will try to prevent the joint from rotating, but will yield to a significant load.</para>
        <para>Here&apos;s a revision of the revolute joint definition above; this time the joint has a limit and a motor enabled. The motor is setup to simulate joint friction.</para>
        <programlisting>
b2RevoluteJointDef jointDef;
jointDef.Initialize(body1, body2, myBody1-&gt;GetWorldCenter());
jointDef.lowerAngle = -0.5f * b2_pi; // -90 degrees
jointDef.upperAngle = 0.25f * b2_pi; // 45 degrees
jointDef.enableLimit = true;
jointDef.maxMotorTorque = 10.0f;
jointDef.motorSpeed = 0.0f;
jointDef.enableMotor = true;
</programlisting>
      </sect2>
      <sect2>
        <title>Prismatic Joint</title>
        <para>A prismatic joint allows for relative translation of two bodies along a specified axis. A prismatic joint prevents relative rotation. Therefore, a prismatic joint has a single degree of freedom.</para>
        <informalfigure>
          <mediaobject>
            <imageobject>
              <imagedata fileref="images/prismaticJoint.gif" format="GIF"/>
            </imageobject>
          </mediaobject>
        </informalfigure>
         <para>The prismatic joint definition is similar to the revolute joint description; just substitute translation for angle and force for torque. Using this analogy provides an example prismatic joint definition with a joint limit and a friction motor:</para>
        <programlisting>
b2PrismaticJointDef jointDef;
b2Vec2 worldAxis(1.0f, 0.0f);
jointDef.Initialize(myBody1, myBody2, myBody1-&gt;GetWorldCenter(), worldAxis);
jointDef.lowerTranslation = -5.0f;
jointDef.upperTranslation = 2.5f;
jointDef.enableLimit = true;
jointDef.motorForce = 1.0f;
jointDef.motorSpeed = 0.0f;
jointDef.enableMotor = true;
</programlisting>
        <para>The revolute joint has an implicit axis coming out of the screen. The prismatic joint needs an explicit axis parallel to the screen. This axis is fixed in the two bodies and follows their motion.</para>
        <para>Like the revolute joint, the prismatic joint translation is zero when the joint is created using <literal>Initialize()</literal>. So be sure zero is between your lower and upper translation limits.</para>
      </sect2>
      <sect2>
        <title>Pulley Joint</title>
        <para>A pulley is used to create an idealized pulley. The pulley connects two bodies to ground and to each other. As one body goes up, the other goes down. The total length of the pulley rope is conserved according to the initial configuration.</para>
        <programlisting>
length1 + length2 == constant
        </programlisting>
        <informalfigure>
          <mediaobject>
            <imageobject>
              <imagedata fileref="images/pulleyJoint.gif" format="GIF"/>
            </imageobject>
          </mediaobject>
        </informalfigure>
         <para>You can supply a ratio that simulates a <emphasis>block and tackle</emphasis>. This causes one side of the pulley to extend faster than the other. At the same time the constraint force is smaller on one side than the other. You can use this to create mechanical leverage.</para>
        <programlisting>
length1 + ratio * length2 == constant
        </programlisting>
        <para>For example, if the ratio is 2, then length1 will vary at twice the rate of length2. Also the force in the rope attached to body1 will have half the constraint force as the rope attached to body2.</para>
        <para>Pulleys can be troublesome when one side is fully extended. The rope on the other side will have zero length. At this point the constraint equations become singular (bad). Therefore the pulley joint constrains the maximum length that either side can attain. Also, you may want to control the maximum lengths for gameplay reasons. So the maximum lengths improve stability and give you more control.</para>
        <para>Here is an example pulley definition:</para>
        <programlisting>
b2Vec2 anchor1 = myBody1-&gt;GetWorldCenter();
b2Vec2 anchor2 = myBody2-&gt;GetWorldCenter();
b2Vec2 groundAnchor1(p1.x, p1.y + 10.0f);
b2Vec2 groundAnchor2(p2.x, p2.y + 12.0f);
float32 ratio = 1.0f;
b2PulleyJointDef jointDef;
jointDef.Initialize(myBody1, myBody2, groundAnchor1, groundAnchor2, anchor1, anchor2, ratio);
jointDef.maxLength1 = 18.0f;
jointDef.maxLength2 = 20.0f;
</programlisting>
      </sect2>
      <sect2>
        <title>Gear Joint</title>
        <para>If you want to create a sophisticated mechanical contraption you might want to use a gears. In priciple you can create gears in Box2D by using compound shapes to model gear teeth. This is not very efficient and might be tedious to author. You also have to be careful to line up the gears so the teeth mesh smoothly. Box2D has a simpler method of creating gears: the <emphasis>gear joint</emphasis>.</para>
        <informalfigure>
          <mediaobject>
            <imageobject>
              <imagedata fileref="images/gearJoint.gif" format="GIF"/>
            </imageobject>
          </mediaobject>
        </informalfigure>
         <para>The gear joint requires the you have two bodies connected to ground by a revolute or prismatic joint. You can use any combination of those joint types. Also, Box2D requires that the revolute and prismatic joints were created with the ground as body1.</para>
        <para>Like the pulley ratio, you can specify a gear ratio. However, in this case the gear ratio can be negative. Also keep in mind that when one joint is a revolute joint (angular) and the other joint is prismatic (translation), then the gear ratio with have units of length or one over length.</para>
        <programlisting>
coordinate1 + ratio * coordinate2 == constant
        </programlisting>
        <para>Here is an example gear joint:</para>
        <programlisting>
b2GearJointDef jointDef;
jointDef.body1 = myBody1;
jointDef.body2 = myBody2;
jointDef.joint1 = myRevoluteJoint;
jointDef.joint2 = myPrismaticJoint;
jointDef.ratio = 2.0f * b2_pi / myLength;
</programlisting>
        <para>Note that the gear joint depends on two other joints. This creates a fragile situation. What happens if those joints are deleted?</para>
        <caution>
          <para>Always delete gear joints before the revolute/prismatic joints on the gears. Otherwise your code will crash in a bad way due to the orphaned joint pointers in the gear joint. You should also delete the gear joint before you delete any of the bodies involved.</para>
        </caution>
      </sect2>
      <sect2>
      <title>Mouse Joint</title>
      <para>The mouse joint is used in the testbed to manipulate bodies with the mouse. Please see the testbed and b2MouseJoint.h for details.</para>
      </sect2>
    </sect1>
    
    <sect1>
      <title>Joint Factory</title>
      <para>Joints are created and destroyed using the world factory methods. This brings up an old issue:</para>
      <caution>
        <para>Don&apos;t try to create a body or joint on the stack or on the heap using <literal>new</literal> or <literal>malloc</literal>. You must create and destroy bodies and joints using the create and destroy methods of the <classname>b2World</classname> class.</para>
      </caution>
      <para>Here&apos;s an example of the lifetime of a revolute joint:</para>
      <programlisting>
b2RevoluteJointDef jointDef;
jointDef.body1 = myBody1;
jointDef.body2 = myBody2;
jointDef.anchorPoint = myBody1-&gt;GetCenterPosition();
b2RevoluteJoint* joint = myWorld-&gt;CreateJoint(&amp;jointDef);
... do stuff ...
myWorld-&gt;DestroyJoint(joint);
joint = NULL;
</programlisting>
      <para>It is always good to nullify your pointer after they are destroyed. This will make the program crash in a controlled manner if you try to reuse the pointer.</para>
      <para>The lifetime of a joint is not simple. Heed this warning well:</para>
      <caution>
        <para>Joints are destroyed when an attached body is destroyed.</para>
      </caution>
      <para>This precaution is not always necessary. You may organize your game engine so that joints are always destroyed before the attached bodies. In this case you don&apos;t need to implement the listener class. See <xref linkend="implicit_destruction"/> for details.</para>
    </sect1>
    <sect1>
      <title>Using Joints</title>
      <para>Many simulations create the joints and don&apos;t access them again until they are detroyed. However, there is a lot of useful data contained in joints that you can use to create a rich simulation.</para>
      <para>First of all, you can get the bodies, anchor points, and user data from a joint.</para>
      <programlisting>
b2Body* GetBody1();
b2Body* GetBody2();
b2Vec2 GetAnchor1();
b2Vec2 GetAnchor2();
void* GetUserData();
</programlisting>
      <para>All joints have a reaction force and torque. This the reaction force applied to body 2 at the anchor point. You can use reaction forces to break joints or trigger other game events. These functions may do some computations, so don&apos;t call them if you don&apos;t need the result.</para>
      <programlisting>
b2Vec2 GetReactionForce();
float32 GetReactionTorque();
</programlisting>
      <sect2>
        <title>Using Distance Joints</title>
        <para>Distance joints don&apos;t have motors or limits, so there are no extra runtime methods for distance joints.</para>
      </sect2>
      <sect2>
        <title>Using Revolute Joints</title>
        <para>You can access a revolute joint&apos;s angle, speed, and motor torque.</para>
        <programlisting>
float32 GetJointAngle() const;
float32 GetJointSpeed() const;
float32 GetMotorTorque() const;
</programlisting>
        <para>You also update the motor parameters each step.</para>
        <programlisting>
void SetMotorSpeed(float32 speed);
void SetMaxMotorTorque(float32 torque);
</programlisting>
        <para>Joint motors have some interesting abilities. You can update the joint speed every time step so you can make the joint move back-and-forth like a sine-wave or according to whatever function you want.</para>
        <programlisting>
... Game Loop Begin ...
myJoint-&gt;SetMotorSpeed(cosf(0.5f * time));
... Game Loop End ...
</programlisting>
        <para>You can also use joint motors to track a desired joint angle. For example:</para>
        <programlisting>
... Game Loop Begin ...
float32 angleError = myJoint-&gt;GetJointAngle() - angleTarget;
float32 gain = 0.1f;
myJoint-&gt;SetMotorSpeed(-gain * angleError);
... Game Loop End ...
</programlisting>
        <para>Generally your gain parameter should not be too large. Otherwise your joint may become unstable.</para>
      </sect2>
      <sect2>
        <title>Using Prismatic Joints</title>
        <para>Using a prismatic joint is similar to using a revolute joint. Here are the relevant member functions:</para>
        <programlisting>
float32 GetJointTranslation() const;
float32 GetJointSpeed() const;
float32 GetMotorForce() const;
void SetMotorSpeed(float32 speed);
void SetMotorForce(float32 force);
</programlisting>
      </sect2>
      <sect2>
        <title>Using Pulley Joints</title>
        <para>Pully joints provide the current lengths.</para>
        <programlisting>
float32 GetLength1() const;
float32 GetLength2() const;
</programlisting>
      </sect2>
      <sect2>
        <title>Using Gear Joints</title>
        <para>Gear joints don&apos;t provide any information beyond the functions defined in <classname>b2Joint</classname>.</para>
      </sect2>
      <sect2>
        <title>Using Mouse Joints</title>
        <para>The mouse joint is able to manipulate the attached body by updating the target point each time step.</para>
      </sect2>
    </sect1>
</chapter>
  
<chapter>
    <title>Contacts</title>
    <sect1>
      <title>About</title>
      <para>Contacts are objects created by Box2D to manage collision between shapes. There are different kinds of contacts, derived from <classname>b2Contact</classname>, for managing contact between different kinds of shapes. For example there is a contact class for managing polygon-polygon collision and another contact class for managing circle-circle collision. This is normally not important to you, I just thought you might like to know.</para>
      <para>Here is some terminlogy associated with contacts. This terminology is particular to Box2D, but you might find similar terminology in other physics engines.</para>
      <glosslist>
        <glossentry>
          <glossterm>contact point</glossterm>
          <glossdef>
            <para>A contact point is a point where two shapes touch. In reality objects may touch over regions when surfaces touch. Box2D approximates contact with a small number of points.</para>
          </glossdef>
        </glossentry>
        <glossentry>
          <glossterm>contact normal</glossterm>
          <glossdef>
            <para>A contact normal is a unit vector that points from shape1 to shape2.</para>
          </glossdef>
        </glossentry>
        <glossentry>
          <glossterm>contact separation</glossterm>
          <glossdef>
            <para>Separation is the opposite of penetration. Separation is negative when shapes overlap. It is possible that future versions of Box2D will create contact points with positive separation, so you may want to check the sign when contact points are reported.</para>
          </glossdef>
        </glossentry>
        <glossentry>
          <glossterm>normal force</glossterm>
          <glossdef>
            <para>Box2D use an iterative contact solver and stores the results with the contact points. You can safely use the normal force to guage the collision intensity. For example, you can use the force to trigger breakables or to play collision sounds.</para>
          </glossdef>
        </glossentry>
        <glossentry>
          <glossterm>tangent force</glossterm>
          <glossdef>
            <para>The tangent force is the contact solver's estimate of the friction force.</para>
          </glossdef>
        </glossentry>
        <glossentry>
          <glossterm>contact ids</glossterm>
          <glossdef>
            <para>Box2D tries to re-use the contact force results from a time step as the initial guess for the next time step. Box2D uses contact ids to match contact points across time steps. The ids contain geometric features indices that help to distinguish one contact point from another.</para>
          </glossdef>
        </glossentry>
       </glosslist>
      <para>Contacts are created when two shape&apos;s AABBs overlap. Sometimes collision filtering will prevent the creation of contacts. Box2D sometimes needs to create a contact even though the collision is filtered. In this case it uses a <classname>b2NullContact</classname> that prevents collision from occuring. Contacts are destroyed with the AABBs cease to overlap.</para>
      <para>So you might gather that there may be contacts created for shapes that are not touching (just their AABBs). Well, this is correct. It&apos;s a &quot;chicken or egg&quot; problem. We don&apos;t know if we need a contact object until one is created to analyze the collision. We could delete the contact right away if the shapes are not touching, or we can just wait until the AABBS stop overlapping. Box2D takes the latter approach.</para>
    </sect1>
    <sect1>
      <title>Contact Listener</title>
      <para>You can receive contact data by implementing <classname>b2ContactListener</classname>. This listener reports a contact point when it is created, when it persists for more than one time step, and when it is destroyed. Keep in mind that two shapes may have multiple contact points.</para>
      <programlisting>
class MyContactListener : public b2ContactListener
{
public:
	void Add(const b2ContactPoint* point)
    {
        // handle add point
    }
    
	void Persist(const b2ContactPoint* point)
    {
        // handle persist point
    }
    
	void Remove(const b2ContactPoint* point)
    {
        // handle remove point
    }
    
    void Result(const b2ContactResult* point)
    {
        // handle results
    }
};</programlisting>
        <caution>
            <para>Do not keep a reference to the contact points returned to <classname>b2ContactListener</classname>.
            Instead make a deep copy of the contact point data into your own buffer. The example below shows one way of doing this.</para>
        </caution>
        <para>Continuous physics uses sub-stepping, so a contact point may be added and removed within the same time step. This is normally not a problem, but your code should handle this gracefully.</para>
        <para>Contact points are reported immediately when they are added, persisted, or removed. This occurs before the solver is called, so the <structname>b2ContactPoint</structname> object does not contain the computed impulse. However, the relative velocity at the contact point is provided so that you can estimated the contact impulse. If you implement the <function>Result</function> listener function, you will receive <structname>b2ContactResult</structname> objects for solid contact points after the solver has been called. These result structures contain the sub-step impulses. Again, due to continuous physics you may receive multiple results per contact point per <function>b2World::Step</function>.</para>
        <para>It is tempting to implement game logic that alters the physics world inside a contact callback. For example, you may have a collision that applies <emphasis>damage</emphasis> and try to destroy the associated actor and its rigid body. However, Box2D does not allow you to alter the physics world inside a callback because you might destroy objects that Box2D is currently processing, leading to orphaned pointers. </para>
        <para>The recommended practice for processing contact points is to buffer all contact points that you care about and process them after the time step. You should always process the contact points immediately after the time step, otherwise some other client code might alter the physics world, invalidating the contact buffer. When you process the contact point buffer you can alter the physics world, but you still need to be careful that you don't orphan pointers stored in the contact point buffer. The testbed has example contact point processing that is safe from orphaned pointers.</para>
        <para>This code from the CollisionProcessing test shows how to handle orphaned bodies when processing the contact buffer. Here is an excerpt. Be sure to read the comments in the listing. This code assumes that all contact points have been buffered in the <classname>b2ContactPoint</classname> array <varname>m_points</varname>.</para>
        <programlisting><![CDATA[
// We are going to destroy some bodies according to contact
// points. We must buffer the bodies that should be destroyed
// because they may belong to multiple contact points.
const int32 k_maxNuke = 6;
b2Body* nuke[k_maxNuke];
int32 nukeCount = 0;

// Traverse the contact buffer. Destroy bodies that
// are touching heavier bodies.
for (int32 i = 0; i < m_pointCount; ++i)
{
    ContactPoint* point = m_points + i;

    b2Body* body1 = point->shape1->GetBody();
    b2Body* body2 = point->shape2->GetBody();
    float32 mass1 = body1->GetMass();
    float32 mass2 = body2->GetMass();

    if (mass1 > 0.0f && mass2 > 0.0f)
    {
        if (mass2 > mass1)
        {
            nuke[nukeCount++] = body1;
        }
        else
        {
            nuke[nukeCount++] = body2;
        }

        if (nukeCount == k_maxNuke)
        {
            break;
        }
    }
}

// Sort the nuke array to group duplicates.
std::sort(nuke, nuke + nukeCount);

// Destroy the bodies, skipping duplicates.
int32 i = 0;
while (i < nukeCount)
{
    b2Body* b = nuke[i++];
    while (i < nukeCount && nuke[i] == b)
    {
        ++i;
    }

    m_world->DestroyBody(b);
}
]]></programlisting>
    </sect1>
    <sect1>
      <title>Contact Filtering</title>
      <para>Often in a game you don&apos;t want all objects to collide. For example, you may want to create a door that only certain characters can pass through. This is called contact filtering, because some interactions are <emphasis>filtered out</emphasis>.</para>
      <para>Box2D allows you to achieve custom contact filtering by implementing a <classname>b2ContactFilter</classname> class. This class requires you to implement a <methodname>ShouldCollide</methodname> function that receives two <classname>b2Shape</classname> pointers. Your function returns true if the shapes should collide.</para>
      <para>The default implementation of <methodname>ShouldCollide</methodname> uses the <structname>b2FilterData</structname> defined in <xref linkend="shapes"/>.</para>
        <programlisting><![CDATA[
bool b2ContactFilter::ShouldCollide(b2Shape* shape1, b2Shape* shape2)
{
	const b2FilterData& filter1 = shape1->GetFilterData();
	const b2FilterData& filter2 = shape2->GetFilterData();

	if (filter1.groupIndex == filter2.groupIndex && filter1.groupIndex != 0)
	{
		return filter1.groupIndex > 0;
	}

	bool collide = (filter1.maskBits & filter2.categoryBits) != 0 && (filter1.categoryBits & filter2.maskBits) != 0;
	return collide;
}
]]></programlisting>
    </sect1>
</chapter>

<chapter>
    <title>Loose Ends</title>
    <sect1 id="world_boundary">
    <title>World Boundary</title>
    <para>You can implement a <classname>b2BoundaryListener</classname> that allows <classname>b2World</classname> to inform you when a body has gone outside the world AABB. When you get the callback, you shouldn&apos;t try to delete the body, instead you should mark the parent actor for deletion or error handling. After the physics time step, you should handle the event.</para>
    <programlisting>
class MyBoundaryListener : public b2BoundaryListener
{
    void Violation(b2Body* body)
    {
        MyActor* myActor = (MyActor*)body-&gt;GetUserData();
        myActor-&gt;MarkForErrorHandling();
    }
};</programlisting>
    <para>You can then register an instance of your boundary listener with your world object. You should do this during world initialization.</para>
    <programlisting>
        myWorld-&gt;SetListener(myBoundaryListener);</programlisting>
    </sect1>
 
    <sect1 id="implicit_destruction">
        <title>Implicit Destruction</title>
        <para>Box2D doesn&apos;t use reference counting. So if you destroy a body it is really gone. Accessing a pointer to a destroyed body has undefined behavior. In other words, your program will likely crash and burn. To help fix these problems, the debug build memory manager fills destroyed entities with <literal>FDFDFDFD</literal>. This can help find problems more easily in some cases.</para>
        <para>If you destroy a Box2D entity, it is up to you to make sure you remove all references to the destroyed object. This is easy if you only have a single reference to the entity. If you have multiple references, you might consider implementing a <emphasis>handle</emphasis> class to wrap the raw pointer.</para>
        <para>Often when using Box2D you will create and destroy many bodies, shapes, and joints. Managing these entities is somewhat automated by Box2D. If you destroy a body then all associated shapes and joints are automatically destroyed. This is called <emphasis>implicit destruction</emphasis>.</para>
        <para>When you destroy a body, all its attached shapes, joints, and contacts are destroyed. This is called <emphasis>implicit destruction</emphasis>. Any body connected to one of those joints and/or contacts is woken. This process is usually convenient. However, you must be aware of one crucial issue:</para>
        <caution>
            <para>When a body is destroyed, all shapes and joints attached to the body are automatically destroyed. You must nullify any pointers you have to those shapes and joints. Otherwise, your program will <emphasis>die horribly</emphasis> if you try to access or destroy those shapes or joints later.</para>
        </caution>
        <para>To help you nullify your joint pointers, Box2D provides a listener class named <classname>b2WorldListener</classname> that you can implement and provide to your world object. Then the world object will notify you when a joint is going to be implicity destroyed.</para>
        <para>Implicit destruction is a great convenience in many cases. It can also make your program fall apart. You may store pointers to shapes and joints somewhere in your code. These pointers become orphaned when an associated body is destroyed. The situation becomes worse when you consider that joints are often created by a part of the code unrelated to management of the associated body. For example, the testbed creates a <classname>b2MouseJoint</classname> for interactive manipulation of bodies on the screen.</para>
        <para>Box2D provides a callback mechanism to inform your application when implicit destruction occurs. This gives your application a chance to nullify the orphaned pointers. This callback mechanism is described later in this manual.</para>
        <para>You can implement a <classname>b2DestructionListener</classname> that allows <classname>b2World</classname> to inform you when a shape or joint is implicitly destroyed because an associated body was destroyed. This will help prevent your code from accessing orphaned pointers.</para>
        <programlisting>
class MyDestructionListener : public b2DestructionListener
{
    void SayGoodbye(b2Joint* joint)
    {
        // remove all references to joint.
    }
};</programlisting>
        <para>You can then register an instance of your destruction listener with your world object. You should do this during world initialization.</para>
        <programlisting>
myWorld-&gt;SetListener(myDestructionListener);</programlisting>
    </sect1>
</chapter>
    
<chapter>
    <title>Settings</title>
    <sect1>
        <title>About</title>
        <para>There are two source files included in Box2D that are supplied specifically for user customization. These are <filename>b2Settings.h</filename> and <filename>b2Settings.cpp</filename>.</para>
        <para>Box2D works with floating point numbers, so some tolerances have to be used to make Box2D perform well.</para>
    </sect1>
    <sect1>
      <title>Tolerances</title>
      <para>There are many tolerances settings that depend on using MKS units. See <xref linkend="units"/> for a deeper explanation of the unit system. See the doxygen docs for explanation of the individual tolerances.</para>
    </sect1>
    <sect1>
      <title>Memory Allocation</title>
      <para>All of Box2D's memory allocations are funnelled through <function>b2Alloc</function> and <function>b2Free</function> except in the following cases.</para>
      <itemizedlist>
        <listitem><para><classname>b2World</classname> can be built on the stack or with whatever allocator you like.</para></listitem>
        <listitem><para>Any other Box2D class that you create without using a factory method. This includes things like callbacks classes and contact point buffers.</para></listitem>
      </itemizedlist>
      <para>Feel free to redirect the allocation by modifying <filename>b2Settings.cpp</filename>.</para>
    </sect1>
</chapter>

<chapter>
    <title>Debug Drawing</title>
        <para>You can implement the <classname>b2DebugDraw</classname> class to get detailed drawing of the physics world.
    Here are the available entities:</para>
        <itemizedlist>
            <listitem><para>shape outlines</para></listitem>
            <listitem><para>joint connectivity</para></listitem>
            <listitem><para>core shapes (for continuous collision)</para></listitem>
            <listitem><para>broad-phase axis-aligned bounding boxes (AABBs), including the world AABB</para></listitem>
            <listitem><para>polygon oriented bounding boxes (OBBs)</para></listitem>
            <listitem><para>broad-phase pairs (potential contacts)</para></listitem>
            <listitem><para>center of mass</para></listitem>
        </itemizedlist>
        <para>This the preferred method of drawing these physics entities, rather than accessing the data directly. The reason is that much of the necessary data is internal and subject to change.</para>
        <para>The testbed draws physics entities using the debug draw facility and the contact listener, so it serves as the primary example of how to implement debug drawing as well as how to draw contact points.</para>
        <screenshot>
          <mediaobject>
            <imageobject>
              <imagedata fileref="images/debugDraw.gif" format="GIF"/>
            </imageobject>
          </mediaobject>
        </screenshot>
</chapter>
</book>
